from django import forms
from django.core.exceptions import ValidationError
import re
from workapp.models import User


def email_validator(email):
    if re.match(r'^[0-9a-zA-Z_]{0,20}@[0-9a-zA-Z]{0，15}\.[com,cn,net]{1,3}$', str(email)):
        print('correct email!')
    else:
        raise ValidationError('请输入正确的邮箱')

def username_validator(username):
    if len(username) > 14:
        raise ValidationError('请输入14个字符以内的用户名')

def usercheck_validator(username):
    users = User.objects.all()
    for user in users:
        if user.name == username:
            raise ValidationError('已存在该用户名')

def password_validator(password):
    if len(password) < 6:
        raise ValidationError('请输入6个字符以上的密码')



class LoginForm(forms.Form):
    email = forms.EmailField(
        widget = forms.TextInput(attrs={'placeholder': '邮箱'}),
        error_messages = {'required': '请输入邮箱'},
        validators=[email_validator]
    )
    password = forms.CharField(
        widget = forms.TextInput(attrs={'placeholder': '密码'}),
        error_messages = {'required': '请输入密码'},
        validators=[password_validator]
    )


class RegisterForm(forms.Form):
    email = forms.EmailField(
        widget = forms.TextInput(attrs={'placeholder': '邮箱'}),
        error_messages = {'required': '请输入邮箱'},
        validators=[email_validator]
    )
    username = forms.CharField(
        widget = forms.TextInput(attrs={'placeholder': '用户名'}),
        error_messages = {'required': '请输入用户名'},
        validators=[username_validator, usercheck_validator]
    )
    password = forms.CharField(
        widget = forms.TextInput(attrs={'placeholder': '密码'}),
        error_messages = {'required': '请输入密码'},
        validators=[password_validator]
    )

class SearchFrom(forms.Form):
    SEARCH_CHOICES = (
        ('1', '人民大学'),
        ('2', '北京大学'),
        ('3', '清华大学'),
    )
    area = forms.CharField(
        widget = forms.Select(choices=SEARCH_CHOICES)
    )
    name = forms.CharField(max_length=50)

class FilterForm(forms.Form):
    TYPE_CHOICES = {
    ('整租','整租'),
    ('合租','合租'),
    ('月租','月租'),
    }

    ARTICLE_CHOICES = {
    ('一室一厅一卫', '一室一厅一卫'),
    ('二室一厅一卫', '二室一厅一卫'),
    ('三室一厅一卫', '三室一厅一卫'),
    ('三室一厅两卫', '三室一厅两卫'),
    ('三室两厅两卫', '三室两厅两卫'),
    ('四室两厅两卫', '四室两厅两卫'),
    }

    INSTALLATIONS_CHOICES = {
    ('独立卫生间','独立卫生间'),
    ('独立阳台','独立阳台'),
    ('厨房','厨房'),
    ('淋浴','淋浴'),
    ('空调','空调'),
    ('电视','电视'),
    ('网络','网络'),
    }

    typehouse = forms.MultipleChoiceField(label='按类型',required=False,widget=forms.RadioSelect,choices=TYPE_CHOICES,)
    housetype = forms.MultipleChoiceField(label='按户型',required=False,widget=forms.CheckboxSelectMultiple,choices=ARTICLE_CHOICES,)
    min_rent = forms.IntegerField(label='最低价')
    max_rent = forms.IntegerField(label='最高价')
    installations  = forms.MultipleChoiceField(label='按设施',required=False,widget=forms.CheckboxSelectMultiple,choices=INSTALLATIONS_CHOICES,)
